from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from core.database import Base
import hashlib


class Log(Base):
    __tablename__ = "log"

    id = Column(Integer, primary_key=True, index=True)
    uri = Column(String)
    operator = Column(String)
    operation_time = Column(DateTime(timezone=True), server_default=func.now())


class User(Base):
    __tablename__ = "user"

    user_id = Column(Integer, primary_key=True, index=True)
    username = Column(String)
    _password = Column("password", String)
    phone = Column(String)
    address = Column(String)
    department_id = Column(Integer, ForeignKey('department.department_id'))

    department = relationship("Department", back_populates="users")

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, plaintext_password):
        self._password = hashlib.md5(plaintext_password.encode()).hexdigest()

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}


class Department(Base):
    __tablename__ = "department"

    department_id = Column(Integer, primary_key=True, index=True)
    department_name = Column(String)

    users = relationship("User", back_populates="department")

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}
